package com.xbjtech.service;

import java.util.List;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbjtech.mapper.UserMapper;
import com.xbjtech.model.User;

@Service
public class UserService extends BaseService<User> {
	
	@Autowired
	UserMapper userMapper;
	
	@Transactional
	public User insertUser(User user) {
		userMapper.insertUseGeneratedKeys(user);
		Integer id = user.getId();
		SimpleHash simpleHash = new SimpleHash("MD5", user.getPassword(), ByteSource.Util.bytes(id + ""), 1);
		user.setPassword(simpleHash.toHex());
		userMapper.updateByPrimaryKeySelective(user);
		return user;
	}
	
	@Autowired
	SqlSessionFactory sqlSessionFactory;
	
	public void insertUserWithRoles(Integer uid, List<Integer> rids) {
		SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
		try {
			UserMapper mapper = session.getMapper(UserMapper.class);
			userMapper.deleteRolesByUid(uid);
			long begin = System.currentTimeMillis();
			for (Integer rid : rids) {
				mapper.insertUserIdAndRoleId(uid, rid);
			}
			long end = System.currentTimeMillis();
			System.out.println("=======" + (end - begin));
			session.commit();
			session.clearCache();
		} catch (RuntimeException e) {
			session.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
	
	
	public List<Integer> selectRolesByUid(Integer uid) {
		return userMapper.selectRolesByUid(uid);
	}
	
	public User selectUsersRoleAndResource(Integer uid) {
		return userMapper.selectUsersRoleAndResource(uid);
	}
	
}
